<template>
	<div class="base-info-page">
		<NavHeader
			:title="$t('install.title', '安装位置')"
			:showStepProgress="true"
			:current="2"
		/>
		<div class="info-card-group">
			<!-- 安装位置 -->
			<div class="info-card clickable" @click="onPositionClick">
				<span class="card-label">{{
					$t('install.position', '安装位置')
				}}</span>
				<span class="card-value">{{
					form.installPosition || $t('install.select', '请选择')
				}}</span>
				<van-icon name="arrow" class="card-arrow" />
			</div>
			<!-- 墙面类型 -->
			<div class="info-card clickable" @click="onWallTypeClick">
				<span class="card-label">{{
					$t('install.wallType', '墙面类型')
				}}</span>
				<span class="card-value">{{
					form.wallType || $t('install.select', '请选择')
				}}</span>
				<van-icon name="arrow" class="card-arrow" />
			</div>

			<!-- 安装位置照片 -->
			<div class="info-card photo-card">
				<div class="photo-header">
					<span class="card-label">{{
						$t('install.photo', '安装位置照片')
					}}</span>
					<span class="photo-tip">{{
						$t(
							'install.photoTip',
							'请尽可能多角度拍摄安装位置，便于技术人员评估'
						)
					}}</span>
				</div>
				<van-uploader
					v-model="form.fileList"
					:max-count="6"
					:before-read="beforeRead"
					:after-read="afterRead"
					multiple
					:deletable="true"
					preview-size="97"
				>
					<template #default>
						<div class="upload-area">
							<van-icon
								name="photograph"
								size="24"
								color="#B1B1B2"
							/>
						</div>
					</template>
				</van-uploader>
			</div>
		</div>
		<div class="bottom-btn-bar">
			<button class="btn-prev" @click="onPrev">
				{{ $t('common.prev', '上一步') }}
			</button>
			<button class="btn-next" @click="onNext">
				{{ $t('common.next', '下一步') }}
			</button>
		</div>
		<!-- 可选：弹窗选择器 -->
		<van-action-sheet
			v-model:show="showWallType"
			:actions="wallTypeOptions"
			@select="selectWallType"
		/>
		<van-action-sheet
			v-model:show="showPosition"
			:actions="positionOptions"
			@select="selectPosition"
		/>
	</div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import NavHeader from '@/components/NavHeader.vue'
import { useRouter, useRoute } from 'vue-router'
import { showFailToast, showToast } from 'vant'
import { uploadFile } from '@/api/user'
import { useOrderStore } from '@/stores/order'
import { getOrderDetailApi } from '@/api/user'
import { useI18n } from 'vue-i18n'

const router = useRouter()
const route = useRoute()
const orderStore = useOrderStore()
const { t } = useI18n()
const form = ref({
	wallType: '',
	installPosition: '',
	fileList: [] as any[],
})

const showWallType = ref(false)
const showPosition = ref(false)
const wallTypeOptions = [
	{ name: t('install.concrete', '混凝土') },
	{ name: t('install.wood', '木板') },
]
const positionOptions = [
	{ name: t('install.surfaceMounted', '墙面surface-mounted') },
	{ name: t('install.flushMounted', '墙里Flush-mounted') },
]

const onWallTypeClick = () => {
	showWallType.value = true
}
const onPositionClick = () => {
	showPosition.value = true
}
const selectWallType = (item: any) => {
	form.value.wallType = item.name
	showWallType.value = false
}
const selectPosition = (item: any) => {
	form.value.installPosition = item.name
	showPosition.value = false
}

const beforeRead = (file: File | File[]) => {
	const files = Array.isArray(file) ? file : [file]
	for (const f of files) {
		if (!['image/jpeg', 'image/png'].includes(f.type)) {
			showFailToast(t('install.onlyJpgPng', '仅支持 JPG/PNG 格式'))
			return false
		}
		if (f.size > 5 * 1024 * 1024) {
			showFailToast(t('install.maxSize', '图片大小不能超过5MB'))
			return false
		}
	}
	return true
}

const afterRead = async (file: any) => {
	// 单文件和多文件都支持
	const files = Array.isArray(file) ? file : [file]
	for (const f of files) {
		// 只赋值，不替换
		if (!(f.file instanceof Blob)) {
			showFailToast(t('install.fileTypeError', '文件类型错误'))
			return
		}
		// 上传
		console.log('afterRead')
		try {
			const res = await uploadFile({ file: f.file })
			const { basePath, fileName } = res.data
			f.url = basePath + fileName
			f.path = fileName
		} catch (e) {
			console.log('afterRead error', e)
			// showFailToast(t('install.uploadFail', '上传失败'))
		}
	}
}

onMounted(async () => {
	// 回显
	form.value.wallType = orderStore.customer.wall_category
	form.value.installPosition = orderStore.customer.install_position
	form.value.fileList = (
		orderStore.customer.install_position_image || []
	).map((url) => ({ url }))
})

function onNext() {
	if (!form.value.wallType) {
		showFailToast(t('install.selectWallType', '请选择墙面类型'))
		return
	}
	if (!form.value.installPosition) {
		showFailToast(t('install.selectPosition', '请选择安装位置'))
		return
	}
	if (form.value.fileList.length === 0) {
		showFailToast(t('install.uploadPhoto', '请上传安装位置照片'))
		return
	}
	// 提交时固定使用中文
	orderStore.customer.wall_category = form.value.wallType || ''
	// 将安装位置转换为固定的中文提交
	let submitPosition = ''
	if (form.value.installPosition === '墙面' || form.value.installPosition === 'Surface-mounted') {
		submitPosition = '墙面'
	} else if (form.value.installPosition === '墙里' || form.value.installPosition === 'Flush-mounted') {
		submitPosition = '墙里'
	} else {
		submitPosition = form.value.installPosition
	}
	orderStore.customer.install_position = submitPosition
	orderStore.customer.install_position_image = form.value.fileList.map(
		(f) => f.url || f.path
	)
	console.log('安装位置信息', orderStore.customer)
	router.push({ name: 'CircuitInfo' })
}

const onPrev = () => router.back()

// 监听表单字段，自动同步到store
watch(
	() => form.value.wallType,
	(val) => {
		orderStore.customer.wall_category = val || ''
	}
)
watch(
	() => form.value.installPosition,
	(val) => {
		// 实时同步时也使用中文格式
		let submitPosition = ''
		if (val === '墙面' || val === 'Surface-mounted') {
			submitPosition = '墙面'
		} else if (val === '墙里' || val === 'Flush-mounted') {
			submitPosition = '墙里'
		} else {
			submitPosition = val || ''
		}
		orderStore.customer.install_position = submitPosition
	}
)
watch(
	() => form.value.fileList,
	(val) => {
		orderStore.customer.install_position_image = val.map(
			(f) => f.url || f.path
		)
	},
	{ deep: true }
)
</script>

<style scoped>
.base-info-page {
	background: #f3f4f6;
	min-height: 100vh;
	padding-bottom: 24px;
}

.info-card-group {
	padding: 16px 0 0 0;
	display: flex;
	flex-direction: column;
	gap: 12px;
	align-items: center;
}

.info-card {
	width: 95%;
	max-width: 450px;
	height: 60px;
	border-radius: 15px;
	background: #fff;
	box-shadow: none;
	margin: 0;
	display: flex;
	align-items: center;
	border: 1px solid #eee;
	padding: 0 16px;
	position: relative;
}

.card-label {
	font-size: 16px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	color: #000;
	letter-spacing: -0.3px;
}

.card-value {
	flex: 1;
	text-align: right;
	font-size: 14px;
	color: #b1b1b2;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	margin-left: 12px;
}

.card-arrow {
	font-size: 20px;
	color: #b1b1b2;
	margin-left: 4px;
}

.photo-card {
	height: auto;
	padding: 16px;
	flex-direction: column;
	align-items: stretch;
}

.photo-header {
	margin-bottom: 12px;
}

.photo-tip {
	display: block;
	font-size: 12px;
	color: #b1b1b2;
	margin-top: 4px;
}

.upload-area {
	width: 97px;
	height: 66px;
	background: #f4f4f4;
	border-radius: 15px;
	display: flex;
	align-items: center;
	justify-content: center;
}

:deep(.van-uploader__preview-image) {
	border-radius: 15px;
}

:deep(.van-uploader__preview-delete) {
	background: rgba(0, 0, 0, 0.5);
}

.bottom-btn-bar {
	position: fixed;
	left: 0;
	bottom: 0;
	width: 100vw;
	display: flex;
	justify-content: center;
	align-items: center;
	background: #fff;
	padding: 12px 0 12px 0;
	z-index: 20;
	gap: 16px;
	box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.03);
}

.btn-prev {
	width: 108px;
	height: 60px;
	border-radius: 10px;
	background: #e7e7e7;
	color: #333a44;
	font-size: 20px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	border: none;
	outline: none;
	letter-spacing: -0.3px;
	cursor: pointer;
}

.btn-next {
	width: 232px;
	height: 60px;
	border-radius: 10px;
	background: #0065d1;
	color: #fff;
	font-size: 20px;
	font-family: 'PingFang SC', sans-serif;
	font-weight: 600;
	border: none;
	outline: none;
	letter-spacing: -0.3px;
	cursor: pointer;
}
</style>
